/**
 * 2017年4月24日
 */
package filter;

import java.io.IOException;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import cn.edu.bjtu.labsys.constant.Constant;

/**
 * 建立分类器模型需要验证用户登陆状态,这里进行用户登陆状态判断
 * 
 * @author Alex
 *
 */
@Component(value = "authFilter")
public class LoginFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse res,
			FilterChain fc) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			String uri = req.getRequestURI().toLowerCase();
			if (uri.endsWith("jpg") || uri.endsWith("png")
					|| uri.endsWith("jpg") || uri.endsWith("gif")) {
				System.out.println("静态资源不应经过这个过滤器的");
				fc.doFilter(request, res);
			} else {
				if (isAuth(req)) {
					fc.doFilter(req, res);
				} else {
					req.getRequestDispatcher("/nologin.jsp").forward(req, res);
				}

			}
		}
	}

	@SuppressWarnings("unchecked")
	private boolean isAuth(HttpServletRequest req) {
		HttpSession session = req.getSession();
		Set<String> set = (Set<String>) session.getAttribute(Constant.SESSION_ATTRIBUTE_AUTH);
		Integer group = (Integer) session.getAttribute(Constant.SESSION_ATTRIBUTE_GROUP);
		String uri = req.getRequestURI();
		System.out.println(uri);
		if(uri.contains("label"))
			return true;
		if ((group!=null && group == 0) || (set!=null && set.contains(uri)))
			return true;
		else
			return false;
	}

	/**
	 * <init-param> <param-name>targetFilterLifecycle</param-name>
	 * <param-value>false</param-value> <!-- 禁用filter init destory方法 -->
	 * </init-param> 这个配置在appcontext.xml值为false所以这个init destory不会执行
	 * 
	 * @param arg0
	 * @throws ServletException
	 */
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("不会执行的");
	}

	@Override
	public void destroy() {
		System.out.println("不会执行的");
	}

}
